# coding: utf-8
# https://github.com/sohow/12306/blob/master/123.php
__author__ = 'fripSide'

import requests
import json
import logging
from datetime import datetime

logging.basicConfig(filename="mp.log", level=logging.DEBUG, format="%(asctime)s | %(levelname)s | %(message)s")

# http://stackoverflow.com/questions/8802945/python-requests-order-get-parameters
# purpose_codes=ADULT&queryDate=2016-02-01&from_station=SZQ&to_station=WHN
# queryDate=2016-02-01&to_station=WHN&purpose_codes=ADULT&from_station=SZQ
params = [
    ("purpose_codes", "ADULT"),
    ("queryDate", "2016-02-01"),
    ("from_station", "SZQ"),
    ("to_station", "WHN"),
]
res = requests.get("https://kyfw.12306.cn/otn/lcxxcx/query", params=params, verify=False)
raw = json.loads(res.text)
"""
"gg_num": "--",
"gr_num": "--",
"qt_num": "--",
"rw_num": "--",
"rz_num": "--",
"tz_num": "--",
"wz_num": "--",
"yb_num": "--",
"yw_num": "--",
"yz_num": "--",
"ze_num": "--",
"zy_num": "--",
"swz_num": "--"
"""

# 监控二等座票 G1312 G1004 G1006

focus = ["G1312", "G1004", "G1006"]


def log(s):
    print(s)
    logging.debug(s)


def get_int(s):
    try:
        return int(s)
    except:
        return 0


msg = ""
SMS_API = "http://yunpian.com/v1/sms/send.json"
SMS_API_KEY = ""
phone = ""

if raw != -1:
    print("query success: %s" % res.url)
    data = raw["data"]["datas"]
    # print(data)
    for item in data:
        # print(item)
        control_flag = int(item.get("controlled_train_flag"))
        train = item.get("station_train_code")
        # print(control_flag)
        if train in focus:
            if control_flag != 1:
                ze_num = get_int(item.get("ze_num"))
                zy_num = get_int(item.get("zy_num"))
                # print("ze_num:" + str(type(ze_num)) + " ")
                if ze_num > 0:
                    msg += train + "有二等座：" + str(ze_num) + "张。"
                if zy_num > 0:
                    msg += train + "有一等座：" + str(ze_num) + "张。"
else:
    print("error request failed: %s" % res.url)

if msg:
    """发送提示短信"""
    log("发送提示短信:" + msg)
    text = "" + msg
    try:
        req = requests.post(SMS_API, data={'apikey': SMS_API_KEY, 'text': text, 'mobile': phone})
        data = json.loads(req.text)
        if data.get('code') != 0:
            logging.info("短信发送失败:" + msg)
    except Exception as e:
        print(e.args + text)
else:
    print(datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ": 没扫描到符合条件的票")
